package cn.tinlan.shopcoin.app.gooddetail;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;
import com.zhouyou.http.subsciber.BaseSubscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.GlideImageLoader;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.app.gooddetail.adapter.GoodDetailListAdapter;
import cn.tinlan.shopcoin.app.gooddetail.model.GoodDetailModel;
import cn.tinlan.shopcoin.app.gooddetail.model.GoodStockModel;
import cn.tinlan.shopcoin.app.gooddetail.view.GoodSizePopupwindow;
import cn.tinlan.shopcoin.app.gooddetail.view.ObservableScrollView;
import cn.tinlan.shopcoin.app.login.LoginActivity;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import io.reactivex.Observable;

/**
 * Created by Mortimer on 2018/11/26. 09:18
 * 佛祖🙏，永无bug。
 */
public class GoodDetailActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.good_detail_main)
    View mainLayout;

    @BindView(R.id.good_detail_scrollview)
    NestedScrollView goodDetailScrollView;
    @BindView(R.id.good_backtop_img)
    ImageView backTopImg;
    private int scrollY = 0;// 标记上次滑动位置

    private View contentView;


    @BindView(R.id.good_detail_banner)
    Banner gooddetail_banner;
    @BindView(R.id.good_detail_titlebar)
    TitleBar gooddetail_titlebar;
    @BindView(R.id.good_tv_title)
    TextView good_title;
    @BindView(R.id.good_tv_newprice)
    TextView good_newprice;
    @BindView(R.id.good_tv_oldprice)
    TextView good_oldprice;
    @BindView(R.id.good_sold_num)
    TextView good_soldnum;
    @BindView(R.id.good_ll_name)
    TextView good_ll_name;

    //图片列表
    @BindView(R.id.good_rv_img)
    RecyclerView good_rv;

//    @BindView(R.id.detial_web_content)
//    FrameLayout frameLayout;
//    WebView mWebView;

    @BindView(R.id.add_shopcar_btn)
    Button addShopCarBtn;
    @BindView(R.id.go_shopping_btn)
    Button goShoppingBtn;

//    TextView addCartNumTv;

    private GoodDetailListAdapter goodDetailListAdapter;
    private List<String> goodImgLists = new ArrayList<>();;

    private String goodId;
    private int goodNumbers = 1;
    private GoodDetailModel goodDetailModel;
    private List<GoodStockModel> goodStockModels;

//    /**
//     * 商品选择类型
//     */
//    public static final int    GOOD_TYPE_Car  = 1;
//    public static final int    GOOD_TYPE_Buy = 2;
    private int clickBtnType = 1;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_good_detail;
    }

    @Override
    public void initData() {
        super.initData();

        goodId = getIntent().getStringExtra("goods_id");
//        gooddetail_titlebar.setTitle(getIntent().getStringExtra("title"));

        loadDetailData();
        loadGoodStocks();
    }

    @Override
    public void initView() {
        super.initView();

        drawableDefaultBar();

        initTitleBar();
        initBanner();
        initRView();
        initScrollView();
        initBottomView();


    }
    //底部加入购物车和立即购买
    private void initBottomView() {
        addShopCarBtn.setOnClickListener(this);
        goShoppingBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_shopcar_btn:
                clickBtnType = 1;
                break;
            case R.id.go_shopping_btn:
                clickBtnType = 2;
                break;
        }

        ToastUtils.show("请到福链完成购物，敬请期待");
//        if (SPUtils.getIsLogin(GoodDetailActivity.this)) {
//            showPopupwindow();
//        }else {
//            startActivity(new Intent(GoodDetailActivity.this, LoginActivity.class));
//        }
    }


    private void showPopupwindow( ) {
        GoodSizePopupwindow sizePopWin = new GoodSizePopupwindow(this, goodDetailModel,new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()) {
                    case R.id.good_popwin_btn:
                        joinShoppingCar();
                        break;

                }
            }
        });
//        View contentView = sizePopWin.getContentView();
//        addCartNumTv = ((TextView) contentView.findViewById(R.id.pop_good_num));
        //设置Popupwindow显示位置（从底部弹出）
        sizePopWin.showAtLocation(mainLayout, Gravity.BOTTOM| Gravity.CENTER_HORIZONTAL, 0, 0);
        //当弹出Popupwindow时，背景变半透明
//        darkenBackgroud(0.4f);
        //设置Popupwindow关闭监听，当Popupwindow关闭，背景恢复1f
        sizePopWin.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

        sizePopWin.setOnGoodSizeChooseListener(new GoodSizePopupwindow.OnGoodSizeChooseListener() {
            @Override
            public void OnGoodSizeChooseResult(String size, String size2) {

            }

            @Override
            public void OnGoodNumResult(int num) {
                Log.d("num",num+"");
            }
        });
    }


    private void initTitleBar() {
        gooddetail_titlebar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
    }

    private void initRView() {

//        mWebView = new WebView(getApplicationContext());
//        frameLayout.addView(mWebView);
//
//        mWebView.setWebViewClient(new WebViewClient(){
//            @Override
//            public void onPageFinished(WebView view, String url) {//页面加载完成
////                progressBar.setVisibility(View.GONE);
//            }
//
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
////                progressBar.setVisibility(View.VISIBLE);
//            }
//
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
////                Log.i("ansen","拦截url:"+url);
////                if(url.equals("http://www.google.com/")){
////                    Toast.makeText(MainActivity.this,"国内不能访问google,拦截该url",Toast.LENGTH_LONG).show();
////                    return true;//表示我已经处理过了
////                }
//                return super.shouldOverrideUrlLoading(view, url);
//            }
//
//        });
//
//        WebSettings webSettings= mWebView.getSettings();
//        webSettings.setJavaScriptEnabled(true);

        LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) ;
        //{
        //            @Override
        //            public boolean canScrollVertically() {
        //                return false;
        //            }
        //        }
        good_rv.setLayoutManager(llm);
        good_rv.setNestedScrollingEnabled(false);
        good_rv.setHasFixedSize(true);
        goodImgLists = new ArrayList<>();

        goodDetailListAdapter = new GoodDetailListAdapter(this,R.layout.view_gooddetail_item,goodImgLists);
        good_rv.setAdapter(goodDetailListAdapter);
//
    }

    public void initBanner() {


        gooddetail_banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setImageLoader(new GlideImageLoader())
                .setImages(goodImgLists)
                .setBannerAnimation(Transformer.Default)
                .isAutoPlay(true)
                .setIndicatorGravity(BannerConfig.CENTER)
                .start();


    }

    @Override
    public void onStart() {
        super.onStart();
        gooddetail_banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        gooddetail_banner.stopAutoPlay();
    }

    private void initScrollView() {
        if (contentView == null) {
            contentView = goodDetailScrollView.getChildAt(0);
        }
        backTopImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodDetailScrollView.post(new Runnable() {
                    @Override
                    public void run() {
//                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);滚动到底部
//                        scrollView.fullScroll(ScrollView.FOCUS_UP);滚动到顶部
//
//                        需要注意的是，该方法不能直接被调用
//                        因为Android很多函数都是基于消息队列来同步，所以需要一部操作，
//                        addView完之后，不等于马上就会显示，而是在队列中等待处理，虽然很快，但是如果立即调用fullScroll， view可能还没有显示出来，所以会失败
//                                应该通过handler在新线程中更新
                        goodDetailScrollView.fullScroll(ScrollView.FOCUS_UP);
                    }
                });
                backTopImg.setVisibility(View.GONE);

            }
        });


        goodDetailScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int i, int y, int i2, int i3) {
                if(y>600){
                    backTopImg.setVisibility(View.VISIBLE);
                }else {
                    backTopImg.setVisibility(View.INVISIBLE);
                }
            }
        });
//        goodDetailScrollView.setOnScollChangedListener(new ObservableScrollView.OnScollChangedListener() {
//            @Override
//            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
//
//
//            }
//        });
    }


    private void loadDetailData() {
        EasyHttp.get(Constants.GoodsDetail)
                .params("id",goodId)
                .execute(new CallBackProxy<CustomApiResult<GoodDetailModel>, GoodDetailModel>(new SimpleCallBack<GoodDetailModel>() {
                    @Override
                    public void onError(ApiException e) {
                        //请求错误
                    }

                    @Override
                    public void onSuccess(GoodDetailModel response) {
                        //请求成功
                        goodDetailModel = response;
                        List<String> tempList = Arrays.asList(goodDetailModel.getImages().split(","));
                        for (int i=0; i<tempList.size();i++) {
                            goodImgLists.add(Constants.IMGURL+tempList.get(i));
                        }
                        gooddetail_banner.update(goodImgLists);



                        good_title.setText(goodDetailModel.getIntro());
                        good_newprice.setText("￥"+goodDetailModel.getPrice());
                        good_oldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                        good_oldprice.setText("￥"+goodDetailModel.getMarket_price());
                        good_soldnum.setText("库存"+goodDetailModel.getStock()+"件");
                        good_ll_name.setText("名称：                   "+goodDetailModel.getName());

//
//                        mWebView.loadData(goodDetailModel.getContent(),"text/html;charset=utf-8","utf-8");
                        goodDetailListAdapter.setNewData(goodImgLists);
    }

}) {
        });

    }
    //加入购物车
    private void joinShoppingCar() {

        EasyHttp.post(Constants.AddGoodsToCar)
                .params("goods_id",goodId)
                .params("user_id",SPUtils.getUserID(GoodDetailActivity.this))
                .params("buy_num",""+goodNumbers)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.show("添加失败");
                    }

                    @Override
                    public void onSuccess(String s) {

                        ToastUtils.show("添加成功");
                    }
                }) {
                });
    }


    private void  loadGoodStocks() {
        Observable<List<GoodStockModel>> observable = EasyHttp.get(Constants.GoodsDetailStock)
                .params("goods_id", goodId)
                .execute(new CallClazzProxy<CustomApiResult<List<GoodStockModel>>, List<GoodStockModel>>(new TypeToken<List<GoodStockModel>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<GoodStockModel>>() {
            @Override
            public void onError(ApiException e) {


            }

            @Override
            public void onNext(List<GoodStockModel> GoodStockModels) {
                super.onNext(GoodStockModels);
                goodStockModels = GoodStockModels;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mWebView.removeAllViews();
//        ((ViewGroup) mWebView.getParent()).removeView(mWebView);
//        mWebView.setTag(null);
//        mWebView.clearHistory();
//        mWebView.destroy();
//        mWebView= null;


    }
}
